<template>
  <div class="app-container container">
    <div class="this_main">
      <div class="main-left">
        <el-button type="text" @click="typeAdd">添加</el-button>
        <el-tree
          :show-checkbox="false"
          @current-change="nodeclick"
          check-strictly
          :data="rootOptions"
          :props="defaultProps"
          highlight-current
          node-key="id"
          :load="loadNode"
          lazy
        >
          <span class="custom-tree-node " slot-scope="{ node, data }">
            <span>{{ node.label }}</span>
            <span class="tree-control">
              <el-tooltip
                class="item"
                effect="dark"
                content="编辑"
                placement="top-end"
              >
                <i
                  class="el-icon-edit"
                  style="color:blue"
                  @click.stop="typeEdit(data)"
                />
              </el-tooltip>
              <el-tooltip
                class="item"
                effect="dark"
                content="删除"
                placement="top-end"
              >
                <i
                  class="el-icon-delete"
                  style="color:red"
                  @click.stop="typeDelete(node, data)"
                />
              </el-tooltip>
            </span>
          </span>
        </el-tree>
      </div>
      <div class="main-right">
        <!--工具栏-->
        <div class="head-container">
          <div v-if="crud.props.searchToggle" v-formkey="{query:crud.toQuery}">
            <el-form size="small" label-width="100px">
              <el-row :gutter="10">
                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
                  <el-form-item label="查询内容">
                    <el-input
                      v-model="query.caName"
                      placeholder="按照资产名称进行查询"
                    />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
                  <el-form-item label="作废状态">
                    <el-select
                      clearable=""
                      v-model="query.caStatus"
                      class="edit-input"
                      placeholder="请选择"
                      style="width: 100%"
                    >
                      <el-option
                        v-for="(item, index) in statusList"
                        :key="index"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
                  <rrOperation :crud="crud" />
                </el-col>
              </el-row>
            </el-form>
          </div>
          <crudOperation>
            <el-tooltip
              slot="right"
              class="item"
              content="新增"
              effect="dark"
              placement="top-start"
            >
              <el-button
                :loading="syncLoading"
                class="filter-item"
                icon="el-icon-add"
                size="mini"
                type="success"
                @click="addFixedAssets"
                >新增
              </el-button>
            </el-tooltip>
          </crudOperation>
        </div>
        <!--表格渲染-->
        <el-table
          ref="table"
          border
          class="this-table"
          v-loading="crud.loading"
          :data="crud.data"
          height="100%"
          style="width: 100%"
          @selection-change="crud.selectionChangeHandler"
        >
          <!-- <el-table-column
            :render-header="crud.renderHeader"
            type="selection"
            width="55"
            align="center"
          /> -->
          <el-table-column
            :render-header="crud.renderHeader"
            v-if="columns.visible('caCode')"
            :show-overflow-tooltip="true"
            label="资产编号"
            align="center"
            prop="caCode"
          />
          <el-table-column
            :render-header="crud.renderHeader"
            v-if="columns.visible('caName')"
            :show-overflow-tooltip="true"
            label="资产名称"
            align="center"
            prop="caName"
          />
          <el-table-column
            :render-header="crud.renderHeader"
            v-if="columns.visible('typeName')"
            :show-overflow-tooltip="true"
            label="类别"
            align="center"
            prop="typeName"
          />
          <el-table-column
            :render-header="crud.renderHeader"
            v-if="columns.visible('type')"
            :show-overflow-tooltip="true"
            label="规格型号"
            align="center"
            prop="type"
          />
          <el-table-column
            :render-header="crud.renderHeader"
            v-if="columns.visible('num')"
            :show-overflow-tooltip="true"
            label="数量"
            align="center"
            prop="num"
          />
          <el-table-column
            :render-header="crud.renderHeader"
            v-if="columns.visible('price')"
            :show-overflow-tooltip="true"
            label="单价"
            align="center"
            prop="price"
          />
          <el-table-column
            :render-header="crud.renderHeader"
            v-if="columns.visible('amount')"
            :show-overflow-tooltip="true"
            label="金额"
            align="center"
            prop="amount"
          />
          <!-- <el-table-column
            :render-header="crud.renderHeader"
            v-if="columns.visible('price')"
            :show-overflow-tooltip="true"
            label="折旧金额"
            align="center"
            prop="price"
          />
          <el-table-column
            :render-header="crud.renderHeader"
            v-if="columns.visible('price')"
            :show-overflow-tooltip="true"
            label="变卖金额"
            align="center"
            prop="price"
          /> -->
          <el-table-column
            :render-header="crud.renderHeader"
            v-if="columns.visible('bankAccount')"
            :show-overflow-tooltip="true"
            label="银行账户"
            align="center"
            prop="bankAccount"
          />
          <el-table-column
            :render-header="crud.renderHeader"
            v-if="columns.visible('producingArea')"
            :show-overflow-tooltip="true"
            label="产地"
            align="center"
            prop="producingArea"
          />
          <el-table-column
            :render-header="crud.renderHeader"
            v-if="columns.visible('subjectName')"
            :show-overflow-tooltip="true"
            label="科目"
            align="center"
            prop="subjectName"
          />
          <el-table-column
            :render-header="crud.renderHeader"
            v-if="columns.visible('supplier')"
            :show-overflow-tooltip="true"
            label="供应商"
            align="center"
            prop="supplier"
          />
          <el-table-column
            :render-header="crud.renderHeader"
            v-if="columns.visible('manufacturer')"
            :show-overflow-tooltip="true"
            label="制造商"
            align="center"
            prop="manufacturer"
          />
          <el-table-column
            :render-header="crud.renderHeader"
            v-if="columns.visible('inOutType')"
            :show-overflow-tooltip="true"
            label="收支类型"
            align="center"
            prop="inOutType"
          />
          <el-table-column
            :render-header="crud.renderHeader"
            v-if="columns.visible('caStatus')"
            :show-overflow-tooltip="true"
            label="状态"
            align="center"
            prop="caStatus"
          />
          <el-table-column
            :render-header="crud.renderHeader"
            v-if="columns.visible('createTime')"
            label="创建日期"
            align="center"
            prop="createTime"
          >
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            :render-header="crud.renderHeader"
            v-if="columns.visible('userRemark')"
            :show-overflow-tooltip="true"
            label="用户备注"
            align="center"
            prop="userRemark"
          />
          <el-table-column
            :render-header="crud.renderHeader"
            align="center"
            fixed="right"
            label="操作"
            width="160px"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                :disabled="scope.row.caStatus !== '禁用'"
                @click="qiyong(scope.row)"
                style="margin-right: 2px"
                type="text"
                >启用
              </el-button>
              <el-button
                size="mini"
                @click="editFixedAssets(scope.row)"
                style="margin-right: 2px"
                type="text"
                >编辑
              </el-button>
              <el-button
                size="mini"
                style="margin-left: -1px; margin-right: 2px"
                type="text"
                @click="delect(scope.row)"
                >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!--分页组件-->
        <pagination />
      </div>
    </div>
    <!-- 新增分类 -->
    <el-dialog
      :title="addTypeType == 'add' ? '新增资产类别' : '编辑资产类别'"
      :visible.sync="addTypeShow"
      width="30%"
      append-to-body
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="120px"
        class="demo-ruleForm"
      >
        <el-form-item label="类别名称" prop="typeName">
          <el-input v-model="ruleForm.typeName"></el-input>
        </el-form-item>
        <el-form-item label="上级类别" prop="id">
          <treeselect
            v-model="ruleForm.id"
            :normalizer="normalizer"
            :load-options="loadOptions"
            :options="rootOptionsSelect"
            placeholder="选择上级类目"
            @select="selectType"
          />
        </el-form-item>
        <!-- <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')"
            >立即创建</el-button
          >
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item> -->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('ruleForm')"
          >确定</el-button
        >
        <!-- <el-button @click="resetForm('ruleForm')">重置</el-button> -->
      </span>
    </el-dialog>
    <addDialog
      v-if="addDialog.show"
      :is-show="addDialog.show"
      :title="addDialog.title"
      :type="addDialog.type"
      :currentId="currentId"
      :dialog-row="addDialog.dialogRow"
      @closeDialog="hideDialog"
      @getFundList="getFundList"
    />
  </div>
</template>

<script>
import { generator, sync } from "@/api/generator/generator";
import {
  getByParent,
  addOrSave,
  delect,
  caAddOrSave,
  delcaType,
  enableChange
} from "@/api/erp/fixedAssetsMain";
import { downloadFile } from "@/utils/index";
import CRUD, { header, presenter } from "@crud/crud";
import rrOperation from "@crud/RR.operation";
import crudOperation from "@crud/CRUD.operation";
import pagination from "@crud/Pagination";
import { LOAD_CHILDREN_OPTIONS, Treeselect } from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import addDialog from "./addDialog";

// crud交由presenter持有
const defaultCrud = CRUD({ url: "api/ca" });
export default {
  name: "GeneratorIndex",
  components: {
    pagination,
    crudOperation,
    rrOperation,
    Treeselect,
    addDialog
  },
  mixins: [presenter(defaultCrud), header()],
  data() {
    return {
      syncLoading: false,
      defaultProps: {
        children: "children",
        label: "name"
      },
      statusList: [
        {
          label: "启用",
          value: "启用"
        },
        {
          label: "折旧中",
          value: "折旧中"
        },
        {
          label: "变卖",
          value: "变卖"
        },
        {
          label: "禁用",
          value: "禁用"
        }
      ],
      addTypeShow: false,
      addTypeType: "add",
      ruleForm: {
        typeName: "",
        id: 0,
        level: 1,
        _id:null
      },
      currentId: null, // 当前点击的资产分类
      addDialog: {
        type: "add",
        show: false,
        title: "新增资产",
        dialogRow: {}
      },
      rootOptions: [],
      rootOptionsSelect: [{ id: 0, name: "顶级类目", level: 0, children: [] }],
      rules: {
        typeName: [{ required: true, message: "不能未空", trigger: "blur" }],
        id: [{ required: true, message: "不能未空", trigger: "change" }]
      },
      options: []
    };
  },
  created() {
    this.crud.optShow = {
      add: false,
      edit: false,
      del: false,
      download: false
    };
    this.getRootModels();
  },
  methods: {
    toGen(tableName) {
      // 生成代码
      generator(tableName, 0).then(data => {
        this.$notify({
          title: "生成成功",
          type: "success",
          duration: 2500
        });
      });
    },
    toDownload(tableName) {
      // 打包下载
      generator(tableName, 2).then(data => {
        downloadFile(data, tableName, "zip");
      });
    },
    sync() {
      const tables = [];
      this.crud.selections.forEach(val => {
        tables.push(val.tableName);
      });
      this.syncLoading = true;
      sync(tables)
        .then(() => {
          this.crud.refresh();
          this.crud.notify("同步成功", CRUD.NOTIFICATION_TYPE.SUCCESS);
          this.syncLoading = false;
        })
        .then(() => {
          this.syncLoading = false;
        });
    },
    renderContent(h, { node, data, store }) {
      return (
        <span class="custom-tree-node">
          <span>{node.label}</span>
          <span>
            <i class="el-icon-edit" style="color:blue" />
            <i class="el-icon-delete" style="color:red" />
          </span>
        </span>
      );
    },
    typeAdd() {
      this.addTypeType = "add";
      this.addTypeShow = true;
      this.ruleForm.typeName = null;
      this.ruleForm.id = null;
      this.ruleForm._id = null;
    },
    typeEdit(data) {
      console.log(data);
      this.addTypeType = "edit";
      this.addTypeShow = true;
      this.ruleForm.typeName = data.name;
      this.ruleForm.id = data.parentId;
      this.ruleForm._id = data.id;
    },
    typeDelete(node, data) {
      console.log(node, data);
      this.$confirm("即将删除节点分类, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
          delcaType([data.id]).then(response => {
            if (response.status == 200) {
              this.$message({
                type: "success",
                message: "删除成功!"
              });
              this.rootOptions = []
              this.getRootModels();
              this.crud.toQuery();
            } else {
              this.$message({
                type: "error",
                message: "删除失败!"
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消"
          });
        });
    },
    // el-tree懒加载
    loadNode(node, resolve) {
      if (node.level == 0) return;
      console.log(node, resolve, "xxx");
      // if (node.level === 0) {
      //   return resolve([{ name: "region" }]);
      // }
      // if (node.level > 1) return resolve([]);
      const para = {
        parentId: node.data.id,
        level: node.data.level + 1
      };
      let arr = [];
      getByParent(para).then(response => {
        for (let index of response.data.content) {
          let chiledModeInfo = {};
          chiledModeInfo.id = index.id;
          chiledModeInfo.level = index.level;
          chiledModeInfo.parent = index.parent;
          chiledModeInfo.parentId = index.parentId;
          chiledModeInfo.name = index.typeName;
          chiledModeInfo.children = null;
          arr.push(chiledModeInfo);
        }
        setTimeout(() => {
          console.log(arr);
          resolve(arr);
        }, 500);
      });
    },
    // 新增选择节点
    selectType(node, instanceId) {
      console.log(node, instanceId, "新增选择节点");
      this.ruleForm.level = node.level + 1;
    },
    // 新增提交
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          const para = {
            typeName: this.ruleForm.typeName,
            parentId: this.ruleForm.id,
            level: this.ruleForm.level
          };
          if (this.addTypeType == "edit") {
            para.id = this.ruleForm._id
          }
          addOrSave(para).then(response => {
            console.log(response, 999);
            if (response.status == 200) {
              this.addTypeShow = false;
              this.rootOptions = [];
              this.rootOptionsSelect = [
                { id: 0, name: "顶级类目", level: 0, children: [] }
              ];
              this.getRootModels();
              // this.query.typeId = val1.id;
              this.crud.toQuery();
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    normalizer(node) {
      //去掉children=[]的children属性
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
    change(node) {
      // this.aa=node.firstName
      // ...
    },
    /** 初始化树数据 **/
    getRootModels() {
      //初始化数据 只加载根节点
      getByParent({ level: 1, parentId: 0 }).then(response => {
        console.log(response);
        for (let index of response.data.content) {
          let modeInfo = {};
          modeInfo.id = index.id;
          modeInfo.level = index.level;
          modeInfo.parent = index.parent;
          modeInfo.parentId = index.parentId;
          modeInfo.name = index.typeName;
          modeInfo.typeCode = index.typeCode;
          modeInfo.children = null;
          this.rootOptions.push(modeInfo);
          this.rootOptionsSelect.push(modeInfo);
        }
        console.log(this.rootOptions, "获取第一层树");
      });
    },

    /** 加载子节点数据（下拉框树) **/
    loadOptions({ action, parentNode, callback }) {
      console.log(action, parentNode, 666);
      if (action === LOAD_CHILDREN_OPTIONS) {
        //加载点击节点的 子节点
        // level默认从0开始，后台是1开始，所有 +2
        const para = {
          parentId: parentNode.id,
          level: parentNode.level + 1
        };
        getByParent(para).then(response => {
          let arr = [];
          for (let index of response.data.content) {
            let chiledModeInfo = {};
            chiledModeInfo.id = index.id;
            chiledModeInfo.level = index.level;
            chiledModeInfo.parent = index.parent;
            chiledModeInfo.parentId = index.parentId;
            chiledModeInfo.name = index.typeName;
            chiledModeInfo.typeCode = index.typeCode;
            chiledModeInfo.children = null;
            arr.push(chiledModeInfo);
          }
          parentNode.children = arr;
        });
        callback();
      }
    },
    // 点击资产分类
    nodeclick(val1, val2) {
      console.log(val1, val2);
      // alert("点击了节点" + val1.id + val1.name);
      this.currentId = val1.id;
      this.query.typeId = val1.id;
      this.crud.toQuery();
    },
    // 新增后查询
    getFundList() {
      this.crud.toQuery();
    },
    // 启用
    qiyong(row) {
      if (row.caStatus !== "禁用") {
        this.$message({
          message: "仅禁用状态下可以启用",
          type: "error"
        });
        return;
      }
      const para = {
        caStatus: "启用",
        id: row.id
      };
      this.$confirm("即将启用, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          enableChange(para).then(res => {
            if (res.status == 200) {
              this.$message({
                message: "启用成功",
                type: "success"
              });
              this.crud.toQuery();
            } else {
              this.$message({
                message: "启用失败",
                type: "error"
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消"
          });
        });
    },
    // 新增
    addFixedAssets() {
      if (!this.currentId) {
        this.$message({
          message: "请先选中资产分类",
          type: "error"
        });
        return;
      }
      this.addDialog.show = true;
      this.addDialog.type = "add";
    },
    // 编辑
    editFixedAssets(row) {
      this.addDialog.type = "edit";
      this.addDialog.dialogRow = row;
      this.addDialog.show = true;
    },
    /** 删除 **/
    delect(row) {
      this.$confirm("即将删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          delect([row.id]).then(response => {
            if (response.status == 200) {
              this.$message({
                type: "success",
                message: "删除成功!"
              });
              this.crud.toQuery();
            } else {
              this.$message({
                type: "error",
                message: "删除失败!"
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消"
          });
        });
    },

    hideDialog() {
      console.log(111);
      this.addDialog.show = false;
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
  padding: 10px 10px 45px 10px;
  width: 100%;
  position: relative;
}
.this_main {
  position: relative;
  display: flex;
  flex-direction: row;

  .main-left {
    position: relative;
    width: 15%;
    border: 1px solid #ccc;
    display: flex;
    flex-direction: column;
    .el-button {
      color: #000;
      justify-content: flex-end !important;
    }
  }

  .main-right {
    width: 85%;
    height: 820px;
    margin-left: 10px;
    position: relative;
    overflow-x: auto;
    display: flex;
    flex-direction: column;
    .this-table {
      flex: 1;
    }
  }
}
// ::v-deep(.el-form-item) {
//   margin-bottom: 10px !important;
// }

.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
  // 设置颜色
  background-color: #5f95cc !important;
}
.tree-control {
  position: absolute;
  right: 5px;
  // display: flex;
  // justify-content: space-between;
}
</style>
